<?php
namespace phiction;
use \phiction\exceptions\bad_request;

class array_utils
{
    static function has_key(array $a, $key): bool
    {
        return array_key_exists($key, $a);
    }

    static function get(array $a, $key, &$value): bool
    {
        if (self::has_key($a, $key)) {
            $value = $a[$key];
            return true;
        } else {
            return false;
        }
    }

    static function get_or(array $a, $key, $default)
    {
        return self::has_key($a, $key)
            ? $a[$key]
            : $default;
    }

    static function get_or_null(array $a, $key)
    {
        return self::get_or($a, $key, null);
    }

    static function get_or_throw(array $a, $key, \Throwable $ex)
    {
        if (!self::has_key($a, $key)) throw $ex;
        return $a[$key];
    }

    static function get_or_bad_request(array $a, $key, $msg=null)
    {
        if (is_null($msg)) $msg = var_export($key, true) . " required";
        return self::get_or_throw($a, $key, new bad_request($msg));
    }
}

